package com.ruoyi.car.controller;

import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.car.domain.PurchaseOrder;
import com.ruoyi.car.domain.CarInfo;
import com.ruoyi.car.domain.CarCustomer;
import com.ruoyi.car.service.IPurchaseOrderService;
import com.ruoyi.car.service.ICarInfoService;
import com.ruoyi.car.service.ICarCustomerService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 购车订单（订单页、订单详情）Controller
 * 
 * @author yby
 * @date 2025-09-01
 */
@RestController
@RequestMapping("/car/order")
public class PurchaseOrderController extends BaseController
{
    @Autowired
    private IPurchaseOrderService purchaseOrderService;
    
    @Autowired
    private ICarInfoService carInfoService;
    
    @Autowired
    private ICarCustomerService carCustomerService;

    /**
     * 查询购车订单（订单页、订单详情）列表
     */
    @PreAuthorize("@ss.hasPermi('car:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(PurchaseOrder purchaseOrder)
    {
        startPage();
        List<PurchaseOrder> list = purchaseOrderService.selectPurchaseOrderList(purchaseOrder);
        return getDataTable(list);
    }

    /**
     * 导出购车订单（订单页、订单详情）列表
     */
    @PreAuthorize("@ss.hasPermi('car:order:export')")
    @Log(title = "购车订单（订单页、订单详情）", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PurchaseOrder purchaseOrder)
    {
        List<PurchaseOrder> list = purchaseOrderService.selectPurchaseOrderList(purchaseOrder);
        ExcelUtil<PurchaseOrder> util = new ExcelUtil<PurchaseOrder>(PurchaseOrder.class);
        util.exportExcel(response, list, "购车订单（订单页、订单详情）数据");
    }

    /**
     * 获取购车订单（订单页、订单详情）详细信息
     */
    @PreAuthorize("@ss.hasPermi('car:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(purchaseOrderService.selectPurchaseOrderById(id));
    }

    /**
     * 生成订单编号
     */
    @PreAuthorize("@ss.hasPermi('car:order:add')")
    @GetMapping("/generateOrderNo")
    public AjaxResult generateOrderNo()
    {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String randomNum = String.format("%06d", new Random().nextInt(1000000));
        String orderNo = "ORDER" + timestamp + randomNum;
        return success(orderNo);
    }
    
    /**
     * 获取用户列表（用于下拉选择）
     */
    @PreAuthorize("@ss.hasPermi('car:order:list')")
    @GetMapping("/getUserList")
    public AjaxResult getUserList()
    {
        List<CarCustomer> list = carCustomerService.selectCarCustomerList(new CarCustomer());
        return success(list);
    }
    
    /**
     * 获取车辆列表（用于下拉选择）
     */
    @PreAuthorize("@ss.hasPermi('car:order:list')")
    @GetMapping("/getCarList")
    public AjaxResult getCarList()
    {
        CarInfo carInfo = new CarInfo();
        carInfo.setStatus(1L); // 只获取已上架的车辆
        List<CarInfo> list = carInfoService.selectCarInfoList(carInfo);
        return success(list);
    }
    
    /**
     * 获取订单表单初始化数据
     */
    @PreAuthorize("@ss.hasPermi('car:order:list')")
    @GetMapping("/getFormData")
    public AjaxResult getFormData()
    {
        Map<String, Object> data = new HashMap<>();
        
        // 生成订单编号
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String randomNum = String.format("%06d", new Random().nextInt(1000000));
        String orderNo = "ORDER" + timestamp + randomNum;
        data.put("orderNo", orderNo);
        
        // 获取用户列表
        List<CarCustomer> userList = carCustomerService.selectCarCustomerList(new CarCustomer());
        data.put("userList", userList);
        
        // 获取车辆列表（只获取已上架的车辆）
        CarInfo carInfo = new CarInfo();
        carInfo.setStatus(1L);
        List<CarInfo> carList = carInfoService.selectCarInfoList(carInfo);
        data.put("carList", carList);
        
        // 订单状态选项
        Map<String, String> statusOptions = new HashMap<>();
        statusOptions.put("1", "待付定金");
        statusOptions.put("2", "待付全款");
        statusOptions.put("3", "待交付");
        statusOptions.put("4", "已完成");
        statusOptions.put("5", "已取消");
        data.put("statusOptions", statusOptions);
        
        return success(data);
    }

    /**
     * 新增购车订单（订单页、订单详情）
     */
    @PreAuthorize("@ss.hasPermi('car:order:add')")
    @Log(title = "购车订单（订单页、订单详情）", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PurchaseOrder purchaseOrder)
    {
        // 如果订单编号为空，自动生成
        if (purchaseOrder.getOrderNo() == null || purchaseOrder.getOrderNo().trim().isEmpty()) {
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String randomNum = String.format("%06d", new Random().nextInt(1000000));
            purchaseOrder.setOrderNo("ORDER" + timestamp + randomNum);
        }
        
        return toAjax(purchaseOrderService.insertPurchaseOrder(purchaseOrder));
    }

    /**
     * 修改购车订单（订单页、订单详情）
     */
    @PreAuthorize("@ss.hasPermi('car:order:edit')")
    @Log(title = "购车订单（订单页、订单详情）", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PurchaseOrder purchaseOrder)
    {
        return toAjax(purchaseOrderService.updatePurchaseOrder(purchaseOrder));
    }

    /**
     * 删除购车订单（订单页、订单详情）
     */
    @PreAuthorize("@ss.hasPermi('car:order:remove')")
    @Log(title = "购车订单（订单页、订单详情）", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(purchaseOrderService.deletePurchaseOrderByIds(ids));
    }
}
